package nl.dxn.tunnel.codec;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;
import nl.dxn.tunnel.enums.TransferMessageType;
import nl.dxn.tunnel.po.MessageConfig;
import nl.dxn.tunnel.po.TransferMessage;
import nl.dxn.tunnel.serialize.SerializerDispatcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * 自定义信息解码器
 */
public class MessageDecoder extends MessageToMessageDecoder<ByteBuf> {
    public static final SerializerDispatcher SERIALIZER_DISPATCHER = new SerializerDispatcher();
    private static final Logger logger = LoggerFactory.getLogger(MessageDecoder.class);

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) {
        try {
            TransferMessage message = new TransferMessage();
            // 4个字节
            message.setType(TransferMessageType.getMessageType(byteBuf.readInt()));

            int metaByteLength = byteBuf.readInt();
            if (metaByteLength > 0) {
                byte[] metaByte = new byte[metaByteLength];
                byteBuf.readBytes(metaByte);
                MessageConfig meta = SERIALIZER_DISPATCHER.deserialize(metaByte, MessageConfig.class);
                message.setConfig(meta);
            }
            if (byteBuf.isReadable()) {
                byte[] data = ByteBufUtil.getBytes(byteBuf);
                message.setData(data);
            }
            list.add(message);
        } catch (Exception ex) {
            logger.error("", ex);
            //throw ex;
        }
    }
}
